/*!***************************************************
 * @file: cbuf.h
 * @brief: 环形缓冲区
 * @author: ITHAO 
 * @date: 2018.11.23
 * @note: 
 ****************************************************/
#ifndef __CBUF_H__
#define __CBUF_H__

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

typedef unsigned char   uint8;
typedef unsigned short  uint16;
typedef unsigned int    uint32;

 #define min(x,y) ({ \
     typeof(x) _x = (x); \
     typeof(y) _y = (y); \
     (void)(&_x == &_y); \
     _x < _y ? _x : _y;})

struct cbuf {
    uint8 *buffer;
    uint32 size;
    uint32 in;
    uint32 out;
    pthread_mutex_t mutex;
    sem_t sem;
};

static inline void cbuf_reset(struct cbuf *p_cbuf)
{
    p_cbuf->in = p_cbuf->out = 0;
}

static inline uint32 cbuf_len(struct cbuf *p_cbuf)
{
    return p_cbuf->in - p_cbuf->out;
}


extern struct cbuf *cbuf_alloc(uint32 size);
extern void cbuf_free(struct cbuf *p_cbuf); 
extern uint32 cbuf_put(struct cbuf *p_cbuf, uint8 *buffer, uint32 len);
extern uint32 cbuf_get(struct cbuf *p_cbuf, uint8 *buffer, uint32 len);

#endif